package algorithm.exam;

import java.util.Comparator;

/**
 * <p>
 * BubbleSorter TEST
 * </p>
 *
 * @author liyi
 * @since 2024/6/30 20:44
 */
public class BubbleSorterTest {
    public static void main(String[] args) {
        Person p1 = new Person(1);
        Person p2 = new Person(4);
        Person p3 = new Person(2);
        Person[] persons = new Person[3];
        persons[0] = p1;
        persons[1] = p2;
        persons[2] = p3;

        printPersons(persons);

        Sorter sorter = new BubbleSorter();
        sorter.sort(persons);
        printPersons(persons);

        sorter.sort(persons, new Comparator<Person>() {

            @Override
            //故意倒序
            public int compare(Person o1, Person o2) {
                if (o1.getAge() > o2.getAge()) {
                    return -11;
                } else if (o1.getAge() < o2.getAge()) {
                    return 1;
                }
                return 0;
            }
        });

        printPersons(persons);

    }

    private static void printPersons(Person[] persons) {
        System.out.println("***************************");
        for (Person p : persons) {
            System.out.println(p);
        }
    }


    static class Person implements Comparable<Person> {
        private Integer age;


        public Integer getAge() {
            return age;
        }

        public Person(Integer age) {
            this.age = age;
        }

        @Override
        public int compareTo(Person o) {
            if (this.getAge() > o.getAge()) {
                return 1;
            } else if (this.getAge() < o.getAge()) {
                return -1;
            }
            return 0;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "age=" + age +
                    '}';
        }
    }
}
